<?php

class AccessoryPictureController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';


	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Deletes a particular model.
	 * In ajax mode, the grid will be refreshed when the update is successful
	 * , while in normal mode, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$model = $this->loadModel($id);

		if(Yii::app()->request->isAjaxRequest)
		{
			// Stop jQuery from re-initialization
	        Yii::app()->clientScript->scriptMap['jquery.js'] = false;

			if(isset($_POST['action']) && $_POST['action'] == 'confirmDelete')
			{
				$model->delete();
				echo CJSON::encode( array(
					'status' => 'success',
					'content' => '<div class="tips tips-ok">
				        <i class="ico-ok"></i>
				        <div class="cont">
				            <h4>Info</h4>
				            <p>Deleted succussfully.</p>
				        </div>
				    </div>',
					));
				exit;
			}
			else if(isset($_POST['action']))
			{
				echo CJSON::encode( array(
					'status' => 'canceled',
					'content' => '<div class="tips tips-info">
				        <i class="ico-info"></i>
				        <div class="cont">
				            <h4>Info</h4>
				            <p>Deleted canceled.</p>
				        </div>
				    </div>',
					));
				exit;
			}
			else
			{
				echo CJSON::encode( array(
					'status' => 'failure',
					'content' => $this->renderPartial('delete', array(
						'model' => $model ), true, true),
					));
				exit;
			}
		}
		else
		{
			if(isset($_POST['confirmDelete']))
			{
				$model->delete();
				$this->redirect(array('admin'));
			}
			else if(isset($_POST['denyDelete']))
				$this->redirect(array('view','id' => $model->id));
			else
				$this->render('delete', array('model' => $model));
		}
	}

	/**
	 * Deletes unused model.
	 * In ajax mode, the grid will be refreshed when the update is successful
	 * , while in normal mode, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDeleteUnused()
	{
		$criteria = new CDbCriteria;
		$criteria->addCondition('status=2');

		// Unlink all picture unused
		$models=AccessoryPicture::model()->findAll($criteria);
		foreach ($models as $model) {
			$dir=Yii::app()->basePath."/../uploads/accessory/";
			$file=$model->name.".".$model->ext;
			$dh=opendir($dir);
			$fullpath=$dir.$file;
			unlink($fullpath);
			closedir($dh);
			//var_dump($model->cate);
		}
		
		AccessoryPicture::model()->deleteAll($criteria);

		if(isset(Yii::app()->request->isAjaxRequest)) {
			echo CJSON::encode(array(
				'status' => 'success',
				'content' => '<div class="tips tips-ok">
			        <i class="ico-ok"></i>
			        <div class="cont">
			            <h4>Congratulations!</h4>
			            <p>Unused pictures successfully deleted.</p>
			        </div>
			    </div>'
			));
		} else
			$this->redirect(array('index'));

	}

	/**
	 * Manages all models.
	 */
	public function actionIndex()
	{
		$model=new AccessoryPicture('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['AccessoryPicture']))
			$model->attributes=$_GET['AccessoryPicture'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=AccessoryPicture::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='accessory-picture-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	/**
	 * Uploads a picture by AJAX
	 */
	public function actionUpload()
	{
		try{
			$model=new AccessoryPicture;

			// get the file
			$picture_file = CUploadedFile::getInstanceByName('Filedata');
			//var_dump($picture_file);

			if(!$picture_file || $picture_file->getHasError()){
				echo 'Error: Invalid document';
				Yii::app()->end();
			}

			// remember the post params?
			// $yourvar = Yii::app()->request->getParam('yourvarname');
			// $picture_name = $picture_file->name;
			$newName = Util::genRandomString(16);
			//Yii::app()->session['accessoryThumb'] = Util::genRandomString(16).'.'.$picture_file->extensionName;

			$model->name = $newName;
			$model->size = $picture_file->size;
			$model->ext = $picture_file->extensionName;
			//file_put_contents(dirname(__FILE__).'/test.txt',Yii::getPathOfAlias('thepathyousavethefile'));
			//
			// I normally hash(algo, data)ere I use PhpThumb Library instead of this
			// make sure 'thepathyousavethefile' is a writable path

			if($model->save())
			{
				//Yii::app()->session['accessoryPicture'][]= $model->id;

				$picture_file->saveAs(
					Yii::app()->basePath.'/../uploads/accessory/'.$newName.'.'.$picture_file->extensionName
				);
				// Return the file id to the script
				// This will display the thumbnail of the uploaded file to the view
				echo "FILEID:" . Yii::app()->getBaseUrl() .
					'/uploads/accessory/'.
					$newName.'.'.$picture_file->extensionName;
			}
		}
		catch(Exception $e){
			echo 'Error: ' . $e->getMessage();
		}
		Yii::app()->end();

	}
}
